<template>
    <div class="file-manager-page">
        <!-- 顶部标题栏 -->
        <div class="content-header">
            <h1 class="content-title">文件管理</h1>
            <div class="action-buttons">
                <button class="btn btn-primary" @click="switchToSSHClient">
                    <i class="fas fa-terminal"></i> SSH连接
                </button>
            </div>
        </div>

        <!-- 文件管理器 -->
        <div class="file-manager">
            <div class="file-manager-header">
                <div
                    class="form-group"
                    style="margin-bottom: 0; margin-right: 15px; flex: 1"
                >
                    <label style="margin-bottom: 5px">选择服务器</label>
                    <select
                        id="fileServerSelect"
                        v-model="currentFileServerId"
                        @change="onServerChange"
                    >
                        <option value="">选择服务器...</option>
                        <option
                            v-for="server in savedServers"
                            :key="server.id"
                            :value="server.id"
                        >
                            {{ server.name }} ({{ server.host }}:{{
                                server.port
                            }})
                        </option>
                    </select>
                </div>

                <div class="file-path">
                    <button
                        class="btn btn-secondary"
                        @click="goToParentDirectory"
                        :disabled="currentPath === '/'"
                    >
                        <i class="fas fa-arrow-up"></i>
                    </button>
                    <input
                        type="text"
                        v-model="currentPath"
                        @change="navigateToPath"
                    />
                    <button class="btn btn-primary" @click="refreshFiles">
                        <i class="fas fa-sync"></i>
                    </button>
                </div>

                <div class="file-actions">
                    <button class="btn btn-success" @click="uploadFile">
                        <i class="fas fa-upload"></i> 上传
                    </button>
                    <button class="btn btn-secondary" @click="createDirectory">
                        <i class="fas fa-folder-plus"></i> 新建文件夹
                    </button>
                </div>
            </div>

            <div class="file-grid">
                <div v-if="loading" class="loading-indicator">
                    <i class="fas fa-spinner fa-spin"></i> 加载中...
                </div>

                <div v-if="errorMessage" class="alert alert-danger">
                    {{ errorMessage }}
                </div>

                <div
                    v-if="!loading && !errorMessage && files.length === 0"
                    class="empty-state"
                >
                    <i class="fas fa-folder-open"></i>
                    <p>当前目录为空</p>
                </div>

                <div
                    v-for="file in files"
                    :key="file.name"
                    class="file-item"
                    @click="handleFileClick(file)"
                >
                    <div class="file-icon">
                        <i
                            v-if="file.isDirectory"
                            class="fas fa-folder"
                            style="color: #ffb142"
                        ></i>
                        <i
                            v-else
                            class="fas fa-file"
                            style="color: #45aaf2"
                        ></i>
                    </div>
                    <div class="file-name">{{ file.name }}</div>
                    <div class="file-size">{{ formatFileSize(file.size) }}</div>
                    <div class="file-date">{{ formatDate(file.modified) }}</div>
                    <div class="file-actions">
                        <button
                            class="btn btn-secondary btn-sm"
                            @click.stop="downloadFile(file)"
                        >
                            <i class="fas fa-download"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 提示框 -->
        <div
            v-if="alertMessage"
            :class="['alert', 'alert-' + alertType]"
            @click="clearAlert"
        >
            {{ alertMessage }}
        </div>
    </div>
</template>

<script>
import menu from "@/views/pages/system/components/menu";
import { moduleName } from "@/config";

export default {
    data: () => ({
        description: "文件管理",
        buttons: {
            search: { name: "查询" },
            add: { name: "添加" },
            restore: { name: "恢复出厂设置" },
            edit: { name: "编辑" },
            del: { name: "删除" },
            addChild: { name: "添加子级" },
            addBtn: { name: "添加按钮" },
        },
        // type 0:目录 1：菜单 2：按钮
        type: "1",
        icon: "FolderOpened",
        name: "文件管理",
        parentMenu: menu,
        module: moduleName,
    }),
};
</script>
<script setup>
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";

// 路由
const router = useRouter();

// 状态管理
const savedServers = ref([]);
const currentFileServerId = ref("");
const currentPath = ref("/");
const files = ref([]);
const loading = ref(false);
const errorMessage = ref("");
const alertMessage = ref("");
const alertType = ref("");

// 加载保存的服务器
const loadSavedServers = async () => {
    try {
        const response = await fetch("/api/servers");
        const servers = await response.json();
        savedServers.value = servers;
    } catch (error) {
        console.error("加载服务器列表失败:", error);
        showAlert("加载服务器列表失败", "danger");
    }
};

// 服务器选择变化
const onServerChange = () => {
    if (currentFileServerId.value) {
        currentPath.value = "/";
        loadFiles();
    } else {
        files.value = [];
    }
};

// 加载文件列表
const loadFiles = async () => {
    if (!currentFileServerId.value) {
        showAlert("请先选择服务器", "info");
        return;
    }

    loading.value = true;
    errorMessage.value = "";

    try {
        const response = await fetch(
            `/api/servers/${currentFileServerId.value}/files?path=${encodeURIComponent(currentPath.value)}`,
        );

        if (!response.ok) {
            throw new Error("获取文件列表失败");
        }

        const data = await response.json();
        files.value = data.files;
    } catch (error) {
        console.error("加载文件失败:", error);
        errorMessage.value = error.message;
    } finally {
        loading.value = false;
    }
};

// 刷新文件列表
const refreshFiles = () => {
    loadFiles();
};

// 处理文件点击
const handleFileClick = (file) => {
    if (file.isDirectory) {
        navigateToDirectory(file.name);
    }
};

// 导航到目录
const navigateToDirectory = (directoryName) => {
    if (currentPath.value === "/") {
        currentPath.value = `/${directoryName}`;
    } else {
        currentPath.value = `${currentPath.value}/${directoryName}`;
    }
    loadFiles();
};

// 导航到指定路径
const navigateToPath = () => {
    if (currentPath.value === "" || currentPath.value[0] !== "/") {
        currentPath.value = "/";
    }
    loadFiles();
};

// 前往父目录
const goToParentDirectory = () => {
    if (currentPath.value === "/") return;

    const pathParts = currentPath.value.split("/").filter((part) => part);
    if (pathParts.length === 0) {
        currentPath.value = "/";
    } else {
        pathParts.pop();
        currentPath.value =
            pathParts.length > 0 ? `/${pathParts.join("/")}` : "/";
    }

    loadFiles();
};

// 下载文件
const downloadFile = async (file) => {
    if (!currentFileServerId.value || file.isDirectory) return;

    try {
        const response = await fetch(
            `/api/servers/${currentFileServerId.value}/files/download?path=${encodeURIComponent(`${currentPath.value}/${file.name}`)}`,
        );

        if (!response.ok) {
            throw new Error("下载文件失败");
        }

        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = file.name;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);

        showAlert(`文件 ${file.name} 下载成功`, "success");
    } catch (error) {
        console.error("下载文件失败:", error);
        showAlert("下载文件失败: " + error.message, "danger");
    }
};

// 上传文件
const uploadFile = () => {
    if (!currentFileServerId.value) {
        showAlert("请先选择服务器", "info");
        return;
    }

    // 创建隐藏的文件输入
    const fileInput = document.createElement("input");
    fileInput.type = "file";
    fileInput.multiple = false;

    fileInput.onchange = async (e) => {
        if (e.target.files.length === 0) return;

        const file = e.target.files[0];
        const formData = new FormData();
        formData.append("file", file);
        formData.append("path", currentPath.value);

        try {
            const response = await fetch(
                `/api/servers/${currentFileServerId.value}/files/upload`,
                {
                    method: "POST",
                    body: formData,
                },
            );

            if (!response.ok) {
                throw new Error("文件上传失败");
            }

            showAlert(`文件 ${file.name} 上传成功`, "success");
            loadFiles(); // 刷新文件列表
        } catch (error) {
            console.error("文件上传失败:", error);
            showAlert("文件上传失败: " + error.message, "danger");
        }
    };

    fileInput.click();
};

// 创建目录
const createDirectory = () => {
    if (!currentFileServerId.value) {
        showAlert("请先选择服务器", "info");
        return;
    }

    const dirName = prompt("请输入新文件夹名称:");
    if (!dirName) return;

    const createDir = async () => {
        try {
            const response = await fetch(
                `/api/servers/${currentFileServerId.value}/files/mkdir`,
                {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify({
                        path: currentPath.value,
                        name: dirName,
                    }),
                },
            );

            if (!response.ok) {
                throw new Error("创建文件夹失败");
            }

            showAlert(`文件夹 ${dirName} 创建成功`, "success");
            await loadFiles(); // 刷新文件列表
        } catch (error) {
            console.error("创建文件夹失败:", error);
            showAlert("创建文件夹失败: " + error.message, "danger");
        }
    };

    createDir();
};

// 格式化文件大小
const formatFileSize = (bytes) => {
    if (bytes === null || bytes === undefined) return "";
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    if (bytes < 1024 * 1024 * 1024)
        return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
    return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
};

// 格式化日期
const formatDate = (dateString) => {
    if (!dateString) return "";
    const date = new Date(dateString);
    return date.toLocaleString();
};

// 显示提示信息
const showAlert = (message, type = "info") => {
    alertMessage.value = message;
    alertType.value = type;

    // 3秒后自动清除提示
    setTimeout(() => {
        alertMessage.value = "";
    }, 3000);
};

// 清除提示
const clearAlert = () => {
    alertMessage.value = "";
};

// 切换到SSH连接页面
const switchToSSHClient = () => {
    router.push("/");
};

// 组件挂载时初始化
onMounted(() => {
    loadSavedServers();
});

// return {
//     savedServers,
//     currentFileServerId,
//     currentPath,
//     files,
//     loading,
//     errorMessage,
//     alertMessage,
//     alertType,
//     loadSavedServers,
//     onServerChange,
//     loadFiles,
//     refreshFiles,
//     handleFileClick,
//     navigateToDirectory,
//     navigateToPath,
//     goToParentDirectory,
//     downloadFile,
//     uploadFile,
//     createDirectory,
//     formatFileSize,
//     formatDate,
//     clearAlert,
//     switchToSSHClient,
// };
</script>

<style scoped>
/* 继承原CSS样式，保持一致的UI体验 */
.file-manager-page {
    padding: 20px;
    height: 100vh;
    box-sizing: border-box;
    background: #f5f7fa;
}

.content-header {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.content-title {
    font-size: 24px;
    font-weight: 600;
    color: #333;
    margin: 0;
}

.action-buttons {
    display: flex;
    gap: 10px;
}

.btn {
    padding: 12px 24px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 500;
    transition: all 0.2s;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    text-decoration: none;
}

.btn-primary {
    background: #1da1f2;
    color: white;
}

.btn-primary:hover {
    background: #1991db;
    transform: translateY(-1px);
}

.btn-success {
    background: #17a2b8;
    color: white;
}

.btn-success:hover {
    background: #138496;
}

.btn-secondary {
    background: #6c757d;
    color: white;
}

.btn-secondary:hover {
    background: #545b62;
}

.btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    transform: none;
}

.btn-sm {
    padding: 4px 8px;
    font-size: 12px;
}

.file-manager {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    height: calc(100% - 100px);
    display: flex;
    flex-direction: column;
}

.file-manager-header {
    padding: 20px;
    border-bottom: 1px solid #e1e8ed;
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: wrap;
}

.form-group {
    display: flex;
    flex-direction: column;
    margin-bottom: 15px;
}

.form-group label {
    margin-bottom: 8px;
    font-weight: 500;
    color: #333;
}

.form-group select {
    padding: 12px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: 14px;
    transition: border-color 0.2s;
}

.form-group select:focus {
    outline: none;
    border-color: #1da1f2;
    box-shadow: 0 0 0 3px rgba(29, 161, 242, 0.1);
}

.file-path {
    display: flex;
    align-items: center;
    gap: 10px;
    flex: 1;
    min-width: 300px;
}

.file-path input {
    flex: 1;
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-family: monospace;
}

.file-actions {
    display: flex;
    gap: 10px;
}

.file-grid {
    padding: 20px;
    overflow-y: auto;
    flex: 1;
}

.file-item {
    display: flex;
    align-items: center;
    padding: 12px;
    border-radius: 6px;
    cursor: pointer;
    transition: background-color 0.2s;
}

.file-item:hover {
    background: #f8f9fa;
}

.file-icon {
    width: 24px;
    margin-right: 12px;
    color: #666;
}

.file-name {
    flex: 1;
    font-weight: 500;
}

.file-size {
    color: #666;
    font-size: 12px;
    margin-right: 15px;
    min-width: 80px;
    text-align: right;
}

.file-date {
    color: #666;
    font-size: 12px;
    margin-right: 15px;
    min-width: 160px;
}

.loading-indicator {
    text-align: center;
    padding: 40px;
    color: #666;
    font-size: 16px;
}

.empty-state {
    text-align: center;
    padding: 60px 20px;
    color: #999;
}

.empty-state i {
    font-size: 48px;
    margin-bottom: 15px;
    opacity: 0.5;
}

.alert {
    padding: 12px 16px;
    margin-bottom: 20px;
    border: 1px solid transparent;
    border-radius: 6px;
    font-size: 14px;
    cursor: pointer;
}

.alert-success {
    color: #155724;
    background-color: #d4edda;
    border-color: #c3e6cb;
}

.alert-danger {
    color: #721c24;
    background-color: #f8d7da;
    border-color: #f5c6cb;
}

.alert-info {
    color: #0c5460;
    background-color: #d1ecf1;
    border-color: #bee5eb;
}

@media (max-width: 768px) {
    .file-manager-header {
        flex-direction: column;
        align-items: stretch;
    }

    .file-path {
        min-width: auto;
    }

    .file-size,
    .file-date {
        display: none;
    }
}
</style>
